<?php namespace Home\Controller; 
//测试控制器
class ListController extends CommonController{

	//构造函数
	public function __init()
	{
	}
	
    //首页
    public function index(){
    	//公共头部title标签数据
    	$conf = array(
			"title"=>"hdphp教学博客-列表页",
		);
		View::with("conf",$conf);
		//接收get参数
		$cid = Q("get.cid",0,'intval');
		$tid = Q("get.tid",0,'intval');
		//实例化分类模型
		$cateModel = new \Common\Model\Category;
		//列表页接收的参数有cid(分类cid),tid(标签tid)
		//如果get接收的是cid,一个分类下面有多少篇文章
		if($cid)
		{
			//递归调用子集，调用分类模型中的getSon
			$cids = $cateModel->getSon($cateModel->get(),$cid);
			//把自己追加进去
			$cids[]=$cid;
			//var_dump($cids);
			//左侧头部数据，有三部分组成 分类，名称，文章总数
			$headData = array("type"=>"分类","name"=>Db::table("category")
					  ->where("cid",$cid)->pluck("cname"),
					  "total"=>Db::table("article")->where("category_cid in(" . implode(",", $cids) . ")")->count()
			);
			//左侧文章的具体内容
			//文章表和分类表进行关联(在页面一个文章列出所属的分类名称)
			$data = Db::table("article") -> join("category", "category_cid", "=", "cid") -> where("is_recycle", 0) -> where("category_cid in (" . implode(",", $cids) . ")") -> get();
			//获得每篇文章所属的标签
			foreach ($data as $k => $v) {
				$data[$k]['tag']=Db::table("article_tag")->join("tag","tag_tid","=","tid")->where("article_aid",$v['aid'])->lists("tid,tname");
				
			}
			//var_dump($data);
		}
		//如果接收的是tid(标签tid)
		if($tid)
		{
			//左侧头部数据
			$headData = array("type"=>"标签",
						"name"=>Db::table("tag")->where("tid",$tid)
						->pluck("tname"),
						"total"=>Db::table("article")->join("article_tag","aid","=","article_aid")->where("is_recycle",0)->where("tag_tid",$tid)->count(),
						
			);
			//处理文章的具体内容
			//获得当前tid所对应的所有文章aid,一个标签对应多少篇文章
			$aids = Db::table("article_tag") -> where("tag_tid", $tid) -> lists("article_aid");
			//如果当前标签（tid）下面有文章
			if($aids) {
				$data = Db::table("article") -> join("category", "category_cid", "=", "cid") -> where("is_recycle", 0) -> where("aid in (" . implode(",", $aids) . ")") -> get();
				foreach ($data as $k => $v) {
					$data[$k]['tag'] = Db::table("article_tag") -> join("tag", "tag_tid", "=", "tid") -> where("article_aid", $v['aid']) -> lists("tid,tname");
				}
			} else {
				//如果标签没有与之相对应的文章
				$data = array();
			}
		}
		
		
			
	   View::with("headData",$headData);
	   View::with("data",$data);
       View::make();
 
    }

}